package com.samphanie.auiu.demo.concurrent.coroutine

import android.util.Log
import com.samphanie.auiu.library.log.AuiuLog
import kotlinx.coroutines.*

/**
 * @author Dries
 **/
object CoroutineScene {

    private val TAG: String = "CoroutineScene"

    /**
     * 以此启动三个线程，并且同步的方式拿到他们的返回值 进而更新UI
     */
    fun startScene1() {
        GlobalScope.launch(Dispatchers.Main) {
            Log.e(TAG, "Coroutine is running")
            val request1 = request1();
            val request2 = request2(request1);
            val request3 = request3(request2);

            updateUI(request3)
        }

        Log.e(TAG, "Coroutine has launched")
    }

    /**
     * 启动一个线程，先执行request1，完了之后，同时运行request2 和 request3. 这两个都结束了执行updateUI
     */
    fun startScene2() {
        GlobalScope.launch(Dispatchers.Main) {
            Log.e(TAG, "Coroutine is running")
            val request1 = request1();
//            val request2 = request2(request1);
//            val request3 = request3(request2);

            val deferre2 = GlobalScope.async { request2(request1) }
            val deferre3 = GlobalScope.async { request3(request1) }

            updateUI(deferre2.await(), deferre3.await())
        }

        Log.e(TAG, "Coroutine has launched")
    }

    private fun updateUI(request: String) {
        Log.e(TAG, "updateUI work on ${Thread.currentThread().name}")
        Log.e(TAG, "paramter:  $request")
    }
    private fun updateUI(request1: String, request2: String) {
        Log.e(TAG, "updateUI work on ${Thread.currentThread().name}")
        Log.e(TAG, "paramter:  $request1 ------ $request2")
    }

    // suspend关键字的作用
    suspend fun request1(): String {
        delay(2*1000) // 不会暂停线程，但会暂停当前所在的协程
        // Thread.sleep(2000) 让线程休眠
        Log.e(TAG, "request1 work on ${Thread.currentThread().name}")
        return "result from request1"
    }
    suspend fun request2(request: String): String {
        delay(2*1000)
        Log.e(TAG, "request2 work on ${Thread.currentThread().name}")
        return "result from request2"
    }
    suspend fun request3(request: String): String {
        delay(2*1000)
        Log.e(TAG, "request3 work on ${Thread.currentThread().name}")
        return "result from request3"
    }

}
